<?php
declare (strict_types = 1);

namespace app\middleware\api;

use app\lib\exception\BaseException;
use think\facade\Cache;

class Auth
{
    /**
     * @param $request
     * @param \Closure $next
     * @return mixed
     * @throws BaseException
     */
    public function handle($request, \Closure $next)
    {
        $params=$request->header();

        if(!array_key_exists('token',$params)) throw new BaseException(['code'=>401,'msg'=>'非法token，禁止登陆！','errorCode'=>401]);
        $token=Cache::get($params['token']);
        if(empty($token)) throw new BaseException(['code'=>400,'msg'=>'token已失效，请重新登陆！','errorCode'=>400]);
        $request->userid=$token;
        return $next($request);
    }
}
